package com.hksj.jetlinks.aop;

import cn.hutool.core.util.ReflectUtil;
import com.hksj.common.config.annotation.CurrentUserIdAndName;
import com.hksj.jetlinks.model.LoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component("jetCurrentUserIdAndNameAspect")
@Aspect
@Order(101)
public class CurrentUserIdAndNameAspect {

    @Before("@annotation(currentUserIdAndName)")
    public void inject(JoinPoint joinPoint, CurrentUserIdAndName currentUserIdAndName){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        LoginUser currentUser = getCurrentUser();
        if (!ObjectUtils.isEmpty(currentUser)){
            Object[] args = joinPoint.getArgs();
            if (!ObjectUtils.isEmpty(args)){
                if (!ObjectUtils.isEmpty(currentUserIdAndName.id())){
                    ReflectUtil.setFieldValue(args[currentUserIdAndName.argIndex()],currentUserIdAndName.id(),currentUser.getUser().getId());
                }

                if (!ObjectUtils.isEmpty(currentUserIdAndName.name())){
                    ReflectUtil.setFieldValue(args[currentUserIdAndName.argIndex()],currentUserIdAndName.name(),currentUser.getUser().getName());
                }
            }
        }
    }

    private LoginUser getCurrentUser(){
        LoginUser currentUser = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof LoginUser){
            currentUser = (LoginUser) principal;
        }
        return currentUser;
    }
}
